package org.swimv2.servlets;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swimv2.entities.FriendshipRequest;
import org.swimv2.entities.User;
import org.swimv2.interfaces.FriendshipManagerRemote;
import org.swimv2.interfaces.SearchManagerRemote;
import org.swimv2.utils.ContextUtil;

/**
 * Servlet implementation class EvalFriendReq
 */
public class EvalFriendReqServlet extends HttpServlet {
	private static final long serialVersionUID = -5578335382630434214L;

	private User page_u, curr_u;
	
	private FriendshipManagerRemote mgr_f = null;
	private SearchManagerRemote     mgr_u = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EvalFriendReqServlet() {
        super();
    }

	/**
	 * Accetta o rifiuta una richiesta di amicizia.
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		try {
			Context ctx = ContextUtil.getInitialContext();
			RequestDispatcher disp;
			
			mgr_f = (FriendshipManagerRemote) ctx.lookup("FriendshipManagerJNDI");
			mgr_u = (SearchManagerRemote)     ctx.lookup("SearchManagerJNDI");
			
			disp = request.getRequestDispatcher("user/profile.jsp");
			
			// L'utente loggato
			curr_u = (User) request.getSession().getAttribute("user");
			// L'utente che ha inviato la richiesta di amicizia
			page_u = mgr_u.getUserById( Integer.parseInt(request.getParameter("u_id")) );
			
			if (curr_u == null || page_u == null || curr_u.getId() == page_u.getId()) {
				request.setAttribute("message_error", "Errore nella gestione della richiesta di amicizia.");
			}
			
			/* Valuta una richiesta di amicizia */
			else {
				String param_how = request.getParameter("how");
				
				/* Accetta richiesta di amicizia */
				if (param_how.equals("accept")) {
					mgr_f.addFriendship(page_u, curr_u);
				}
				/* Rifiuta richiesta di amicizia */
				else if (param_how.equals("reject")) {
					mgr_f.removeFriendshipReq(page_u, curr_u);
				}
				
				request.setAttribute("message", "Valutazione richiesta effettuata.");
			}
			disp.forward(request, response);
		}
		catch (NamingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
